package com.chenyi.leetcode.editor.cn;

import java.util.Arrays;

/**
 * [350]两个数组的交集 II
 *
 * @author by chenyi
 * @className IntersectionOfTwoArraysIi
 * @date 2022-08-27 17:28:18
 */
public class IntersectionOfTwoArraysIi {
    public static void main(String[] args) {
        Solution solution = new IntersectionOfTwoArraysIi().new Solution();
        System.out.println(Arrays.toString(solution.intersect(new int[]{1, 2, 2, 1}, new int[]{2, 2})));
    }

    @SuppressWarnings("AlibabaCommentsMustBeJavadocFormat")
            //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public int[] intersect(int[] nums1, int[] nums2) {
            Arrays.sort(nums1);
            Arrays.sort(nums2);
            int nums1Length = nums1.length;
            int nums2Length = nums2.length;
            int nums1Index = 0;
            int nums2Index = 0;
            int[] arr = new int[Math.max(nums1Length, nums2Length)];
            int arrIndex = 0;
            while (nums1Index < nums1Length && nums2Index < nums2Length) {
                if (nums1[nums1Index] == nums2[nums2Index]) {
//                if (arrIndex == 0 || nums1[nums1Index] != arr[arrIndex - 1]) {
                    arr[arrIndex++] = nums1[nums1Index];
//                }
                    nums1Index++;
                    nums2Index++;
                } else if (nums1[nums1Index] < nums2[nums2Index]) {
                    nums1Index++;
                } else {
                    nums2Index++;
                }
            }
            return Arrays.copyOfRange(arr, 0, arrIndex);
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}
